Popular Searches
Popular Course Categories
Popular Courses

Web Element Operations

Web Element Operations

Selenium with Java

Web Element Operations with Java in Selenium

Web Element Operations are the actions performed on web elements such as text boxes, buttons, links, checkboxes, radio buttons, dropdowns, images, tables, and other HTML elements using Selenium WebDriver with Java.

After Selenium identifies an element using a locator, the returned WebElement can be used to interact with that element, retrieve information from it, verify its state, and perform user-like actions. Selenium's Java API provides methods such as click(), sendKeys(), clear(), getText(), getAttribute(), isDisplayed(), isEnabled(), and isSelected() for common element operations.

Course Resource: Selenium Training | Register for Course Demo


1. What is a Web Element?

A Web Element is an HTML element displayed or represented within a web page. Examples include input fields, buttons, links, checkboxes, radio buttons, dropdowns, headings, paragraphs, images, tables, and containers.

In Selenium Java, a web element is represented by the WebElement interface.

WebElement username = driver.findElement(By.id("username"));

Here:

  • driver is the WebDriver instance.
  • findElement() searches for an element.
  • By.id("username") is the locator.
  • username is the WebElement reference.

A WebElement can also act as a search context, which means Selenium can search for child elements inside an already located element.

2. Why are Web Element Operations Important?

Web element operations are the foundation of UI automation. Finding an element alone is not enough; Selenium must interact with the element to reproduce user actions and verify application behavior.

  • Enter data into forms.
  • Click buttons.
  • Open links.
  • Select checkboxes and radio buttons.
  • Read text from pages.
  • Retrieve attribute values.
  • Check whether elements are visible.
  • Check whether elements are enabled.
  • Check whether checkboxes or radio buttons are selected.
  • Work with dropdowns.
  • Validate application behavior.
  • Automate complete business workflows.

3. Basic Web Element Operation Flow

Open Browser

      |

      v

Open Web Application

      |

      v

Inspect HTML

      |

      v

Choose Locator

      |

      v

findElement()

      |

      v

Get WebElement

      |

      v

Perform Operation

      |

      v

Validate Result

      |

      v

Continue Test

      |

      v

driver.quit()

4. Basic WebElement Syntax

The general syntax for locating a web element is:

WebElement element = driver.findElement(By.id("elementId"));

After obtaining the WebElement, Selenium operations can be performed on it.

element.click();

5. Important WebElement Methods

MethodPurpose
click()Clicks the element
sendKeys()Enters text or keyboard input
clear()Clears text from an editable field
getText()Returns visible rendered text
getAttribute()Retrieves an attribute or runtime property value
isDisplayed()Checks whether the element is displayed
isEnabled()Checks whether the element is enabled
isSelected()Checks whether a selectable element is selected
getTagName()Returns the HTML tag name
getCssValue()Returns a CSS property value
getDomAttribute()Retrieves the declared DOM attribute value
getDomProperty()Retrieves the current DOM property value

6. Locating a Web Element

Before performing an operation, Selenium must identify the target element using a locator.

WebElement username =

    driver.findElement(By.id("username"));

Common locator strategies include:

  • ID
  • Name
  • Class Name
  • Tag Name
  • Link Text
  • Partial Link Text
  • CSS Selector
  • XPath

The findElement() method returns the first matching element, while findElements() returns a collection of matching elements.

7. click() Operation

The click() method is used to click buttons, links, checkboxes, radio buttons, menu items, and other clickable elements.

WebElement loginButton =

    driver.findElement(By.id("login"));

 

loginButton.click();

Example

driver.findElement(By.cssSelector("button.login")).click();

Real-World Example

WebElement submitButton =

    driver.findElement(By.cssSelector("button[type='submit']"));

 

submitButton.click();

8. sendKeys() Operation

The sendKeys() method is used to enter text or keyboard input into an element such as a text box, search field, username field, password field, or textarea.

WebElement username =

    driver.findElement(By.id("username"));

 

username.sendKeys("admin");

Password Example

WebElement password =

    driver.findElement(By.id("password"));

 

password.sendKeys("Password123");

9. clear() Operation

The clear() method removes the existing text from an editable element.

WebElement searchBox =

    driver.findElement(By.id("search"));

 

searchBox.clear();

searchBox.sendKeys("Laptop");

When to Use clear()

  • When a field already contains text.
  • When replacing existing test data.
  • When testing form editing.
  • When reusing the same input field during a test.

10. getText() Operation

The getText() method retrieves the visible rendered text of an element.

WebElement message =

    driver.findElement(By.id("message"));

 

String text = message.getText();

 

System.out.println("Message: " + text);

11. getAttribute() Operation

The getAttribute() method can be used to retrieve a value associated with an element's attribute or runtime property.

WebElement username =

    driver.findElement(By.id("username"));

 

String value = username.getAttribute("value");

 

System.out.println(value);

Getting href

WebElement link =

    driver.findElement(By.linkText("Home"));

 

String href = link.getAttribute("href");

 

System.out.println("Link URL: " + href);

Getting class

String className =

    driver.findElement(By.id("login"))

          .getAttribute("class");

 

System.out.println(className);

12. getDomAttribute() and getDomProperty()

Modern Selenium Java APIs distinguish between a declared DOM attribute and a current DOM property. This distinction is useful when testing values that may change after page load.

WebElement input =

    driver.findElement(By.id("username"));

 

String attributeValue =

    input.getDomAttribute("value");

 

String propertyValue =

    input.getDomProperty("value");

MethodTypical Use
getAttribute()Reads an attribute or applicable runtime value
getDomAttribute()Reads the DOM attribute
getDomProperty()Reads the current DOM property

13. isDisplayed() Operation

The isDisplayed() method checks whether an element is displayed in the current browsing context.

WebElement username =

    driver.findElement(By.id("username"));

 

if (username.isDisplayed()) {

    System.out.println("Username field is visible");

}

14. isEnabled() Operation

The isEnabled() method checks whether an element is enabled for interaction.

WebElement loginButton =

    driver.findElement(By.id("login"));

 

if (loginButton.isEnabled()) {

    loginButton.click();

}

Disabled Button Example

WebElement submit =

    driver.findElement(By.id("submit"));

 

System.out.println(

    "Enabled: " + submit.isEnabled()

);

15. isSelected() Operation

The isSelected() method is commonly used with checkboxes, radio buttons, and other selectable elements.

WebElement checkbox =

    driver.findElement(By.id("terms"));

 

if (!checkbox.isSelected()) {

    checkbox.click();

}

16. Selecting a Radio Button

WebElement maleRadio =

    driver.findElement(By.id("male"));

 

if (!maleRadio.isSelected()) {

    maleRadio.click();

}

17. Selecting a Checkbox

WebElement terms =

    driver.findElement(By.id("terms"));

 

if (!terms.isSelected()) {

    terms.click();

}

18. Deselecting a Checkbox

Selenium does not provide a direct deselect() operation for a normal checkbox. The common approach is to check its current state and click it only when it is selected.

WebElement checkbox =

    driver.findElement(By.id("newsletter"));

 

if (checkbox.isSelected()) {

    checkbox.click();

}

19. Checking Multiple Element States

WebElement element =

    driver.findElement(By.id("submit"));

 

System.out.println("Displayed: " + element.isDisplayed());

System.out.println("Enabled: " + element.isEnabled());

System.out.println("Selected: " + element.isSelected());

20. getTagName() Operation

The getTagName() method returns the HTML tag name of an element.

WebElement element =

    driver.findElement(By.id("username"));

 

String tagName = element.getTagName();

 

System.out.println("Tag: " + tagName);

For example, the returned value may be input, button, div, or a.

21. getCssValue() Operation

The getCssValue() method retrieves the value of a CSS property associated with an element.

WebElement heading =

    driver.findElement(By.tagName("h1"));

 

String fontSize =

    heading.getCssValue("font-size");

 

System.out.println("Font Size: " + fontSize);

Another Example

String display =

    heading.getCssValue("display");

 

System.out.println("Display: " + display);

22. Working with Text Boxes

Text boxes are among the most frequently used web elements in automation.

WebElement username =

    driver.findElement(By.id("username"));

 

username.clear();

username.sendKeys("testuser");

Complete Form Example

WebElement firstName =

    driver.findElement(By.id("firstName"));

 

WebElement lastName =

    driver.findElement(By.id("lastName"));

 

firstName.sendKeys("John");

lastName.sendKeys("Smith");

23. Working with Password Fields

WebElement password =

    driver.findElement(By.id("password"));

 

password.clear();

password.sendKeys("Password123");

24. Working with Textarea

A textarea can be handled similarly to a normal text input.

WebElement comments =

    driver.findElement(By.id("comments"));

 

comments.sendKeys("This is a Selenium test.");

25. Working with Buttons

WebElement loginButton =

    driver.findElement(By.id("loginButton"));

 

if (loginButton.isDisplayed() &&

    loginButton.isEnabled()) {

    loginButton.click();

}

26. Working with Links

WebElement homeLink =

    driver.findElement(By.linkText("Home"));

 

homeLink.click();

Reading Link URL

WebElement link =

    driver.findElement(By.linkText("Products"));

 

String url =

    link.getAttribute("href");

 

System.out.println(url);

27. Working with Images

Images can be located using attributes such as id, alt, src, CSS selectors, or XPath.

WebElement logo =

    driver.findElement(By.cssSelector("img.logo"));

 

String source =

    logo.getAttribute("src");

 

System.out.println("Image URL: " + source);

28. Working with Dropdowns

For a standard HTML <select> element, Selenium provides the Select class.

import org.openqa.selenium.By;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.support.ui.Select;

 

WebElement countryElement =

    driver.findElement(By.id("country"));

 

Select country =

    new Select(countryElement);

 

country.selectByVisibleText("India");

Select by Value

country.selectByValue("IN");

Select by Index

country.selectByIndex(2);

Get All Dropdown Options

List<WebElement> options =

    country.getOptions();

 

for (WebElement option : options) {

    System.out.println(option.getText());

}

29. Checking Selected Dropdown Option

WebElement selectedOption =

    country.getFirstSelectedOption();

 

System.out.println(

    "Selected: " + selectedOption.getText()

);

30. Handling Multiple Select Dropdowns

Some HTML select elements allow multiple options to be selected.

if (country.isMultiple()) {

    country.selectByValue("IN");

    country.selectByValue("US");

}

31. Working with Tables

Tables contain rows and cells that can be located and processed using WebElement collections.

List<WebElement> rows =

    driver.findElements(By.cssSelector("table tbody tr"));

 

for (WebElement row : rows) {

    System.out.println(row.getText());

}

Reading Table Cells

List<WebElement> cells =

    driver.findElements(By.cssSelector("table tbody tr td"));

 

for (WebElement cell : cells) {

    System.out.println(cell.getText());

}

32. Working with Lists of Web Elements

The findElements() method returns a list of matching WebElement objects. If nothing matches, Selenium returns an empty list.

List<WebElement> buttons =

    driver.findElements(By.tagName("button"));

 

System.out.println(

    "Buttons: " + buttons.size()

);

Loop Through Elements

for (WebElement button : buttons) {

    System.out.println(button.getText());

}

33. Performing Operations on Multiple Elements

List<WebElement> checkboxes =

    driver.findElements(

        By.cssSelector("input[type='checkbox']")

    );

 

for (WebElement checkbox : checkboxes) {

    if (!checkbox.isSelected()) {

        checkbox.click();

    }

}

34. Checking Element Text

WebElement message =

    driver.findElement(By.id("message"));

 

String actualMessage =

    message.getText();

 

if (actualMessage.equals("Login successful")) {

    System.out.println("Message verified");

}

35. Checking an Input Value

For input fields, the entered text is commonly represented by the element's value property.

WebElement username =

    driver.findElement(By.id("username"));

 

username.sendKeys("admin");

 

String value =

    username.getAttribute("value");

 

System.out.println("Entered: " + value);

36. Getting Element Attributes

WebElement button =

    driver.findElement(By.id("login"));

 

String id =

    button.getAttribute("id");

 

String className =

    button.getAttribute("class");

 

String type =

    button.getAttribute("type");

 

System.out.println("ID: " + id);

System.out.println("Class: " + className);

System.out.println("Type: " + type);

37. Verifying Element Visibility

WebElement errorMessage =

    driver.findElement(By.id("error"));

 

if (errorMessage.isDisplayed()) {

    System.out.println(

        "Error message is visible"

    );

}

38. Verifying Element Availability

WebElement submit =

    driver.findElement(By.id("submit"));

 

if (submit.isEnabled()) {

    System.out.println(

        "Submit button is enabled"

    );

}

39. Web Element Operations with Explicit Wait

Modern web applications may load or update elements asynchronously. In such cases, a test may need to wait for a required condition before performing an operation.

import java.time.Duration;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;

 

public class ElementWaitExample {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

 

        try {

            driver.get("https://example.com");

 

            WebDriverWait wait =

                new WebDriverWait(

                    driver,

                    Duration.ofSeconds(10)

                );

 

            WebElement username =

                wait.until(

                    ExpectedConditions.visibilityOfElementLocated(

                        By.id("username")

                    )

                );

 

            username.sendKeys("admin");

        } finally {

            driver.quit();

        }

    }

}

40. ElementClickInterceptedException

Sometimes Selenium identifies an element correctly but another element, overlay, popup, or UI component prevents the click operation.

Example situations include:

  • Cookie banners covering the button.
  • Modal dialogs covering the page.
  • Loading overlays.
  • Animations or transitions.
  • Another element positioned above the target.

Use appropriate synchronization and make sure the intended element is interactable before clicking.

41. StaleElementReferenceException

A WebElement reference can become stale when the DOM is refreshed or the element is replaced.

WebElement username =

    driver.findElement(By.id("username"));

 

driver.navigate().refresh();

 

username =

    driver.findElement(By.id("username"));

 

username.sendKeys("admin");

42. NoSuchElementException

A NoSuchElementException can occur when Selenium cannot find an element using the supplied locator.

WebElement username =

    driver.findElement(By.id("wrongId"));

Possible causes include:

  • Incorrect locator.
  • Element not yet loaded.
  • Wrong page.
  • Element inside an iframe.
  • DOM changed after the element was located.
  • Incorrect browsing context.

43. Handling Elements Inside an iframe

If an element belongs to an iframe, Selenium must first switch into the appropriate frame before interacting with the element.

WebElement frame =

    driver.findElement(By.id("paymentFrame"));

 

driver.switchTo().frame(frame);

 

WebElement cardNumber =

    driver.findElement(By.id("cardNumber"));

 

cardNumber.sendKeys("4111111111111111");

 

driver.switchTo().defaultContent();

44. Handling Elements in Nested DOM Structures

WebElement also acts as a search context, so an element can be used as the starting point for locating descendants.

WebElement loginForm =

    driver.findElement(By.id("loginForm"));

 

WebElement username =

    loginForm.findElement(

        By.name("username")

    );

 

username.sendKeys("admin");

This can make locators more scoped and readable when a specific container has been identified.

45. Working with Element Collections Inside a Container

WebElement productList =

    driver.findElement(By.id("products"));

 

List<WebElement> products =

    productList.findElements(By.cssSelector(".product"));

 

for (WebElement product : products) {

    System.out.println(product.getText());

}

46. Keyboard Operations with WebElement

The sendKeys() method can also send keyboard keys to an element.

import org.openqa.selenium.Keys;

 

WebElement search =

    driver.findElement(By.id("search"));

 

search.sendKeys("Selenium");

search.sendKeys(Keys.ENTER);

Ctrl + A Example

search.sendKeys(Keys.CONTROL, "a");

Backspace Example

search.sendKeys(Keys.BACK_SPACE);

47. Tab Key Operation

WebElement username =

    driver.findElement(By.id("username"));

 

username.sendKeys("admin");

username.sendKeys(Keys.TAB);

48. Enter Key Operation

WebElement searchBox =

    driver.findElement(By.name("q"));

 

searchBox.sendKeys("Selenium WebDriver");

searchBox.sendKeys(Keys.ENTER);

49. Form Submission

For many modern applications, clicking the appropriate submit button is preferred. In cases where the form element supports submission, the form can also be submitted through the relevant Selenium API.

WebElement form =

    driver.findElement(By.id("loginForm"));

 

form.submit();

50. Mouse Operations and Web Elements

For advanced mouse interactions, Selenium provides the Actions API. The WebElement can be supplied as the target of the mouse operation.

import org.openqa.selenium.interactions.Actions;

 

WebElement menu =

    driver.findElement(By.id("menu"));

 

Actions actions =

    new Actions(driver);

 

actions.moveToElement(menu).perform();

51. Double Click on a Web Element

WebElement element =

    driver.findElement(By.id("item"));

 

Actions actions =

    new Actions(driver);

 

actions.doubleClick(element).perform();

52. Right Click on a Web Element

WebElement element =

    driver.findElement(By.id("item"));

 

Actions actions =

    new Actions(driver);

 

actions.contextClick(element).perform();

53. Drag and Drop

WebElement source =

    driver.findElement(By.id("source"));

 

WebElement target =

    driver.findElement(By.id("target"));

 

Actions actions =

    new Actions(driver);

 

actions.dragAndDrop(source, target).perform();

54. Scrolling to a Web Element

When an element is outside the visible area, scrolling may be required before interaction.

WebElement element =

    driver.findElement(By.id("footer"));

 

JavascriptExecutor js =

    (JavascriptExecutor) driver;

 

js.executeScript(

    "arguments[0].scrollIntoView({block:'center'});",

    element

);

55. Clicking Through JavaScript

JavaScript execution can sometimes be useful for special situations, but normal WebDriver interaction should generally be preferred when the element is properly interactable.

WebElement button =

    driver.findElement(By.id("login"));

 

JavascriptExecutor js =

    (JavascriptExecutor) driver;

 

js.executeScript(

    "arguments[0].click();",

    button

);

56. Reading Element HTML

An element's HTML-related attributes can be inspected to help verify its structure and state.

WebElement element =

    driver.findElement(By.id("username"));

 

String outerHtml =

    element.getAttribute("outerHTML");

 

System.out.println(outerHtml);

57. Element Operation with Assertions

Web element operations are frequently combined with assertions to verify application behavior.

import static org.testng.Assert.assertTrue;

 

WebElement message =

    driver.findElement(By.id("success"));

 

assertTrue(message.isDisplayed());

Text Assertion

import static org.testng.Assert.assertEquals;

 

String actual =

    driver.findElement(By.id("message"))

          .getText();

 

assertEquals(actual, "Login successful");

58. Complete Login Web Element Operation Example

import java.time.Duration;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;

 

public class LoginElementOperations {

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        try {

            driver.manage().window().maximize();

            driver.get("https://example.com");

 

            WebDriverWait wait =

                new WebDriverWait(

                    driver,

                    Duration.ofSeconds(10)

                );

 

            WebElement username =

                wait.until(

                    ExpectedConditions.visibilityOfElementLocated(

                        By.id("username")

                    )

                );

 

            WebElement password =

                driver.findElement(By.id("password"));

 

            WebElement loginButton =

                driver.findElement(By.id("login"));

 

            username.clear();

            username.sendKeys("admin");

 

            password.clear();

            password.sendKeys("Password123");

 

            if (loginButton.isDisplayed() &&

                loginButton.isEnabled()) {

                loginButton.click();

            }

 

        } finally {

            driver.quit();

        }

    }

}

59. Complete Form Operations Example

WebElement firstName =

    driver.findElement(By.id("firstName"));

 

WebElement lastName =

    driver.findElement(By.id("lastName"));

 

WebElement email =

    driver.findElement(By.id("email"));

 

WebElement terms =

    driver.findElement(By.id("terms"));

 

WebElement submit =

    driver.findElement(

        By.cssSelector("button[type='submit']")

    );

 

firstName.clear();

firstName.sendKeys("John");

 

lastName.clear();

lastName.sendKeys("Smith");

 

email.clear();

email.sendKeys("[email protected]");

 

if (!terms.isSelected()) {

    terms.click();

}

 

if (submit.isEnabled()) {

    submit.click();

}

60. Real-World E-Commerce Web Element Operations

WebElement searchBox =

    driver.findElement(By.id("search"));

 

searchBox.clear();

searchBox.sendKeys("Laptop");

searchBox.sendKeys(Keys.ENTER);

 

WebElement product =

    driver.findElement(

        By.cssSelector(".product-card")

    );

 

System.out.println(

    "Product: " + product.getText()

);

 

WebElement addToCart =

    product.findElement(

        By.cssSelector(".add-to-cart")

    );

 

if (addToCart.isEnabled()) {

    addToCart.click();

}

61. Real-World Registration Form Operations

WebElement firstName =

    driver.findElement(By.id("firstName"));

 

WebElement lastName =

    driver.findElement(By.id("lastName"));

 

WebElement email =

    driver.findElement(By.name("email"));

 

WebElement password =

    driver.findElement(By.name("password"));

 

WebElement terms =

    driver.findElement(By.id("terms"));

 

firstName.sendKeys("John");

lastName.sendKeys("Smith");

email.sendKeys("[email protected]");

password.sendKeys("Password123");

 

if (!terms.isSelected()) {

    terms.click();

}

62. Page Object Model and Web Element Operations

In the Page Object Model, locators and element operations are usually organized inside page classes. This separates page interaction logic from test scenarios and improves maintainability.

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

 

public class LoginPage {

 

    private WebDriver driver;

 

    private By usernameField =

        By.id("username");

 

    private By passwordField =

        By.id("password");

 

    private By loginButton =

        By.id("login");

 

    public LoginPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void enterUsername(String value) {

        driver.findElement(usernameField)

              .clear();

 

        driver.findElement(usernameField)

              .sendKeys(value);

    }

 

    public void enterPassword(String value) {

        driver.findElement(passwordField)

              .clear();

 

        driver.findElement(passwordField)

              .sendKeys(value);

    }

 

    public void clickLogin() {

        driver.findElement(loginButton)

              .click();

    }

}

63. Web Element Operations in PageFactory

Selenium's Java support package also provides PageFactory and annotations such as @FindBy for Page Object implementations.

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.support.FindBy;

import org.openqa.selenium.support.PageFactory;

 

public class LoginPage {

 

    @FindBy(id = "username")

    private WebElement username;

 

    @FindBy(id = "password")

    private WebElement password;

 

    @FindBy(id = "login")

    private WebElement loginButton;

 

    public LoginPage(WebDriver driver) {

        PageFactory.initElements(driver, this);

    }

 

    public void login(

        String user,

        String pass

    ) {

        username.clear();

        username.sendKeys(user);

 

        password.clear();

        password.sendKeys(pass);

 

        loginButton.click();

    }

}

64. Web Element Operations with Dynamic Elements

Dynamic elements may not be immediately available or may change after an AJAX request. In such situations, combine reliable locators with explicit waits.

WebDriverWait wait =

    new WebDriverWait(

        driver,

        Duration.ofSeconds(10)

    );

 

WebElement button =

    wait.until(

        ExpectedConditions.elementToBeClickable(

            By.id("submit")

        )

    );

 

button.click();

65. Web Element Operations with Multiple Matching Elements

List<WebElement> products =

    driver.findElements(

        By.cssSelector(".product")

    );

 

for (WebElement product : products) {

 

    String name = product.getText();

 

    System.out.println(

        "Product: " + name

    );

}

66. Web Element Operation Decision Flow

Locate Element

      |

      v

Get WebElement

      |

      v

Is it Displayed?

      |

     Yes

      |

      v

Is it Enabled?

      |

     Yes

      |

      v

Choose Operation

      |

      +---- sendKeys()

      |

      +---- click()

      |

      +---- clear()

      |

      +---- getText()

      |

      +---- getAttribute()

      |

      +---- isSelected()

      |

      +---- getCssValue()

      |

      v

Validate Result

67. Common Web Element Exceptions

ExceptionTypical CausePossible Solution
NoSuchElementExceptionElement cannot be foundVerify locator, page state, frame, and synchronization
StaleElementReferenceExceptionDOM changed after locating the elementLocate the element again
ElementClickInterceptedExceptionAnother element blocks the clickCheck overlays, scrolling, and synchronization
ElementNotInteractableExceptionElement cannot currently receive the requested interactionCheck visibility, enabled state, and page state
InvalidElementStateExceptionElement is in an unsuitable state for the requested operationVerify the element type and current state
TimeoutExceptionWait condition was not satisfied within the timeoutCheck locator, condition, page state, and timeout

68. Common Web Element Operation Mistakes

  • Trying to interact with an element before locating it.
  • Using an unstable locator.
  • Typing into a disabled field.
  • Clicking before an element becomes interactable.
  • Ignoring overlays and modal dialogs.
  • Using a stale WebElement reference after the DOM changes.
  • Using getText() when the required value is actually stored in an input's value property.
  • Using Select with a custom dropdown that is not an HTML select element.
  • Failing to switch into an iframe before interacting with its elements.
  • Using JavaScript unnecessarily instead of normal WebDriver interaction.
  • Not using explicit waits for asynchronous page behavior.
  • Not closing the browser after the test.

69. Best Practices for Web Element Operations

  1. Use stable and unique locators.
  2. Keep locators readable and maintainable.
  3. Use explicit waits for dynamic elements when synchronization is required.
  4. Check element state when the workflow requires it.
  5. Use clear() before sendKeys() when replacing existing input.
  6. Use getAttribute("value") or the appropriate property when validating input values.
  7. Use getText() for rendered text.
  8. Use isDisplayed(), isEnabled(), and isSelected() when state verification is needed.
  9. Use the Select class only for standard HTML select elements.
  10. Use Actions for advanced mouse interactions.
  11. Use JavaScript execution only when appropriate for the test scenario.
  12. Re-locate elements after a DOM refresh when necessary.
  13. Keep element operations inside Page Object classes in larger frameworks.
  14. Use meaningful variable and method names.
  15. Always clean up the WebDriver session with driver.quit().

70. WebElement vs WebDriver

WebDriverWebElement
Controls the browserRepresents an HTML element
Opens and navigates pagesInteracts with individual elements
Manages browser windowsManages element-level operations
Can locate elementsCan perform actions on located elements
Example: driver.get()Example: element.click()
Example: driver.navigate().back()Example: element.sendKeys()

71. WebElement Operation Quick Revision

OperationJava MethodPurpose
Clickclick()Clicks an element
Enter TextsendKeys()Enters text or keyboard input
Clear Textclear()Removes existing editable text
Read TextgetText()Reads rendered text
Read AttributegetAttribute()Reads an attribute or applicable runtime value
Read DOM AttributegetDomAttribute()Reads a declared DOM attribute
Read DOM PropertygetDomProperty()Reads a current DOM property
VisibilityisDisplayed()Checks whether element is displayed
Enabled StateisEnabled()Checks whether element is enabled
Selected StateisSelected()Checks selected state
Tag NamegetTagName()Returns HTML tag name
CSS ValuegetCssValue()Reads a CSS property

72. Practical Project: Web Element Operations Practice

Build a Selenium Java automation project that demonstrates different WebElement operations on a registration or login page.

Project Requirements

  • Launch Chrome browser.
  • Open a test web application.
  • Locate username and password fields.
  • Clear existing values.
  • Enter username and password.
  • Check whether the login button is displayed.
  • Check whether the login button is enabled.
  • Click the login button.
  • Read the success message.
  • Verify the message text.
  • Read selected attributes.
  • Close the browser using driver.quit().

73. Practical Complete Web Element Operations Program

import java.time.Duration;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;

 

public class WebElementOperations {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        try {

            driver.manage().window().maximize();

 

            driver.get(

                "https://www.selenium.dev/selenium/web/web-form.html"

            );

 

            WebDriverWait wait =

                new WebDriverWait(

                    driver,

                    Duration.ofSeconds(10)

                );

 

            WebElement textBox =

                wait.until(

                    ExpectedConditions.visibilityOfElementLocated(

                        By.name("my-text")

                    )

                );

 

            System.out.println(

                "Displayed: " + textBox.isDisplayed()

            );

 

            System.out.println(

                "Enabled: " + textBox.isEnabled()

            );

 

            textBox.clear();

            textBox.sendKeys("Selenium with Java");

 

            WebElement submitButton =

                wait.until(

                    ExpectedConditions.elementToBeClickable(

                        By.cssSelector("button")

                    )

                );

 

            submitButton.click();

 

            WebElement message =

                wait.until(

                    ExpectedConditions.visibilityOfElementLocated(

                        By.id("message")

                    )

                );

 

            System.out.println(

                "Message: " + message.getText()

            );

 

        } finally {

            driver.quit();

        }

    }

}

74. Interview Questions on Web Element Operations

Q1. What is WebElement in Selenium?

WebElement is the Selenium Java interface used to represent an HTML element and perform operations on that element.

Q2. What is the use of click()?

The click() method is used to perform a click operation on a clickable web element such as a button, link, checkbox, or radio button.

Q3. What is the difference between clear() and sendKeys()?

clear() removes existing text from an editable field, while sendKeys() enters text or keyboard input into the element.

Q4. What is the use of getText()?

getText() retrieves the rendered visible text of an element.

Q5. How do you get the value entered in a text box?

A common approach is to retrieve the value using the element's value attribute or property.

String value =

    driver.findElement(By.id("username"))

          .getAttribute("value");

Q6. What is isDisplayed()?

isDisplayed() checks whether the element is displayed in the current browsing context.

Q7. What is isEnabled()?

isEnabled() checks whether the element is enabled for interaction.

Q8. What is isSelected()?

isSelected() checks whether a selectable element such as a checkbox or radio button is currently selected.

Q9. Can WebElement locate another element?

Yes. WebElement is a SearchContext, so it can be used with findElement() and findElements() to search within that element's context.

Q10. How do you handle a stale WebElement?

When the DOM has changed and the previous reference is stale, locate the element again before performing the operation.

Q11. How do you handle a dropdown?

For a standard HTML select element, locate it and create a Selenium Select object, then use methods such as selectByVisibleText(), selectByValue(), or selectByIndex().

Q12. Why are waits important for WebElement operations?

Modern web applications may update the DOM asynchronously. Appropriate waits help synchronize the test with the required element state before performing an operation.

75. Final Summary

Web Element Operations are the core actions used to automate interactions with web pages using Selenium WebDriver and Java. After locating an element, Selenium allows testers to click it, enter text, clear fields, read text and attributes, check visibility and enabled state, verify selections, work with dropdowns, perform keyboard operations, and execute advanced mouse interactions.

The most frequently used methods include click(), sendKeys(), clear(), getText(), getAttribute(), isDisplayed(), isEnabled(), isSelected(), getTagName(), and getCssValue(). Reliable automation also requires stable locators, proper synchronization, handling of dynamic DOM changes, and correct management of frames and special UI components.

In professional Selenium frameworks, WebElement operations are commonly organized through the Page Object Model, where page-specific locators and interactions are maintained separately from test cases. This improves readability, reuse, and maintainability.


76. Course Resources

Learn more about Selenium Automation Testing:

Selenium Training

Register for a course demo:

Register for Course Demo

whatsapp